const base = {
  data () {
    return {
      baseResolve: null
    }
  },
  methods: {
    uploadBase64 (base64, subSystem = 2, fileOwnerType = 2) {
      return new Promise(resolve => {
        const blob = this.convertBase64UrlToBlob(base64)
        this.computeBaseMD5(blob).then(res => {
          this.uploadBaseFile({
            subSystem: subSystem,
            fileOwnerType: fileOwnerType,
            fileName: `${Math.random().toString(36).substr(2)}.png`,
            fileSize: blob.size,
            fileMine: blob.type,
            uuid: this.getNumber(32),
            blob: blob,
            MD5: res
          })
        })
        this.baseResolve = resolve
      })
    },
    getNumber (num) {
      let data = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
      let result = ''
      for (let i = 0; i < num; i++) {
        let r = Math.floor(Math.random() * 62)
        result += data[r]
      }
      return `${result}.png`
    },
    // 将图片base64编码格式转为blob格式
    convertBase64UrlToBlob (base) {
      const bytes = window.atob(base)
      // 处理异常,将ascii码小于0的转换为大于0
      // const ab = new ArrayBuffer(bytes.length)
      const buffer = new Uint8Array(bytes.length)
      for (let i = 0; i < bytes.length; i++) {
        buffer[i] = bytes.charCodeAt(i)
      }
      return new Blob([buffer.buffer], { type: 'image/png' })
    },
    computeBaseMD5 (blob) {
      return new Promise(resolve => {
        const fileReader = new FileReader()
        fileReader.readAsArrayBuffer(blob)
        fileReader.onload = (evt) => {
          if (evt.target.readyState === FileReader.DONE) {
            let sparkMD5 = new this.$SparkMd5.ArrayBuffer()
            sparkMD5.append(evt.target.result)
            let MD5 = sparkMD5.end()
            resolve(MD5)
          }
        }
      })
    },
    // 上传文件
    async uploadBaseFile (file) {
      await this.uploadBaseFileConfig(file)
      await this.fileBaseSts(file)
      this.initBaseOSS(file)
    },
    initBaseOSS (file) {
      if (file.isUploaded) {
        this.baseResolve(file)
      } else {
        file.clientOSS = new this.$OSS({
          region: 'oss-cn-hangzhou',
          accessKeyId: file.policyInf.accessKeyId,
          accessKeySecret: file.policyInf.accessKeySecret,
          stsToken: file.policyInf.securityToken,
          bucket: file.policyInf.bucket,
          timeout: 180000000
        })
        this.putBlob(file)
      }
    },
    putBlob (file) {
      file.clientOSS.multipartUpload(file.uuid, new Blob([file.blob]), {
        callback: {
          url: file.fileConfig.callBackUrl,
          body: JSON.stringify(file.fileBody),
          contentType: 'application/json'
        }
      }).then(() => {
        this.baseResolve(file)
      })
    },
    // 获取文件配置
    uploadBaseFileConfig (file) {
      return new Promise(resolve => {
        let data = {
          'subSystem': file.subSystem
        }
        this.$axios({
          method: 'post',
          url: `${this.$site.homeServer}/common/uploadFileConfig.htm`,
          closeSaveRequest: true,
          data: this.$qs.stringify(data, {indices: false})
        }).then(res => {
          if (res.data.errorMsg) {
            this.$message.error(res.data.errorMsg)
          } else {
            Object.assign(file, {fileConfig: res.data})
            resolve()
          }
        })
      })
    },
    fileBaseSts (file) {
      return new Promise(resolve => {
        let data = {
          'form.subSystem': file.subSystem,
          'form.fileOwnerType': file.fileOwnerType,
          'form.fileName': file.fileName,
          'form.fileSize': file.fileSize,
          'form.fileType': 1,
          'form.fileMime': file.fileMine,
          'form.fileMd5': file.MD5
        }
        this.$axios({
          method: 'post',
          url: `${this.$site.homeServer}/common/fileSts.htm`,
          closeSaveRequest: true,
          data: this.$qs.stringify(data)
        }).then(res => {
          if (res.data.errorMsg) {
            this.$message.error(res.data.errorMsg)
          } else {
            const {fileList, policyInf} = res.data
            file.fileList = fileList
            file.fileUuid = fileList[0].fileUuid
            file.fileKey = fileList[0].fileKey
            if (fileList[0].fileKey) {
              file.isUploaded = true
            }
            file.uuid = `${file.fileUuid}.png`
            file.policyInf = policyInf
            Object.assign(file, {fileBody: {
              fileKey: file.uuid,
              fileSize: file.fileSize,
              fileMd5: file.MD5,
              fileId: fileList[0].fileUuid
            }})
            resolve()
          }
        })
      })
    }
  }
}
export default base
